package com.wyz.web.interceptor;


import com.alibaba.fastjson.JSON;
import com.wyz.common.util.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${delivery.auth.activate}")
    private boolean activate;

    @Autowired
    private HttpSession sess;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // 不用自己放行了，在webConfig里面设置路径即可
//        // 对注册&登录&注销操作放行
//        String uri = request.getRequestURI();
//        if(uri.startsWith("user")) {
//            return true;
//        }

        // 根据session的用户是否登录
        if (request.getSession().getAttribute("userId") == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try (PrintWriter out = response.getWriter()) {
                Message msg = Message.fail("用户未登录");
                out.append(JSON.toJSONString(msg));
                return false;
            } catch (Exception e) {
                log.error(e.getMessage());
                response.sendError(500);
                return false;
            }
        }
        return true;
    }
}
